package com.ttt.gdfood.service.Imp;

import cn.hutool.crypto.SecureUtil;
import com.ttt.gdfood.entity.User;
import com.ttt.gdfood.mapper.UserMapper;
import com.ttt.gdfood.service.IUserService;
import com.ttt.gdfood.service.ex.PasswordNotMatchException;
import com.ttt.gdfood.service.ex.UserNotFoundException;
import com.ttt.gdfood.service.ex.UsernameDuplicateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UserService implements IUserService {
    @Autowired
    private UserMapper userMapper;

    // 用户注册
    @Override
    public void reg(User user) {
// 根据参数user对象获取注册的用户名
        String phone = user.getPhone();

        User result = userMapper.findByPhone(phone);
// 判定是否存在已注册手机号
        if(result != null){
            throw new UsernameDuplicateException("手机账号已被注册");
        }
// 创建当前时间对象
        Date now = new Date();
// 将密码md5加密
        String password = SecureUtil.md5(user.getPassword());
        user.setPassword(password);
        user.setCreate_time(now);

// 设置默认头像
        user.setAvatar("https://cdn.uviewui.com/uview/album/6.jpg");
// 用户角色默认设为0代表用户
        user.setRole(0);

// 调用持久层Void insert(User user)方法
        userMapper.insertUser(user);

    }

    @Override
    public User login(String phone, String password) {
// 调用userMapper的findByPhone()方法，根据参数phone查询用户数据
        User result = userMapper.findByPhone(phone);
        //return userMapper.findByPhone(phone);
// 判断查询结果是否为null
        if (result == null) {
// 是:抛出UserNotFoundException异常
            throw new UserNotFoundException("用户不存在");
        }
//// 判断查询结果中的isDelete是否为1
//        if (result.getIsDelete() == 1) {
//// 是:抛出UserNotFoundException异常
//            throw new UserNotFoundException("用户数据不存在的错误");
//        }

// 调用getMd5Password()方法，将参数password和salt结合起来进行加密
        String md5Password = SecureUtil.md5(password);
        if (!result.getPassword().equals(md5Password)) {
            throw new PasswordNotMatchException("密码验证失败的错误");

        }
        return result;
    }

    // 根据id删除
    public void deleteById(int id){
        userMapper.deleteById(id);
    }

    // 根据id查找
    public User getUserById(int id){
        return userMapper.findById(id);
    }

    // 根据id修改用户信息
    public void updateUser(User user){
        user.setAvatar("http://8.142.20.59:9000/gdfood/"+user.getAvatar());
        userMapper.updateUser(user);
    }

    // 根据id修改用户信息
    public void updateUserInfo(User user){
        String password = SecureUtil.md5(user.getPassword());
        user.setPassword(password);
        userMapper.updateUserInfo(user);
    }
}
